package com.lbc.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // test1();    //  4641 ms
        // test2();    //  8 ms
         test3();    //  328 ms
    }

    public static void test1() {
        long sum = 0L;
        long start = System.currentTimeMillis();
        //  普通
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+" 时间："+(end-start));
    }
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(1, 10_0000_0000);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//  提交
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("sum="+"时间："+(end-start));
    }
    public static void test3() {
        long start = System.currentTimeMillis();
        //  Stream 并行流  () (]
        //                    区间                         .并行      .规约(求和)
        Long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+" 时间："+(end-start));
    }
}
